/*
 * pulseseq.cpp
 *
 *  Created on: Jun 17, 2011
 *      Author: nzhao
 */
#include "share/pulseseq.h"

double getPulse(int n)
{
	double res;

	switch(SEQ_NAME)
	{
	case 1:
		res = sin( n * PI / 2. / ( PULSE_NUM + 1 ) );
		res *= res;
		break;
	case 2:
			res = ( 2.0 * n - 1.) /( 2. * PULSE_NUM );
		break;
	case 3:
		res = cddpulse(CDD_ORDER, n);
        break;
	default:
		res =  1.;
	}
	return res;
}

int get_CDD_pulse_num(int cdd_order)
{
    if(cdd_order == 1)
        return 1;
    if(cdd_order%2 == 0)
    {
        return 2 * get_CDD_pulse_num(cdd_order-1);
    }
    else
    {
        return 2 * get_CDD_pulse_num(cdd_order-1) + 1;
    }

}

double cddpulse(int cdd_order, int k)
{
    double res, lower_order_pos;
    int npulse, half_n, q;

    npulse = get_CDD_pulse_num(cdd_order);

    if( cdd_order == 1)
    {
        res = 0.5 * k;
        return res;
    }
    if( npulse % 2 == 1 && k == (npulse + 1 ) / 2 )
        return 0.5;

    half_n = npulse % 2 == 0 ? npulse / 2 : ( npulse + 1) / 2;
    q = k > half_n ? k - half_n : k;

    lower_order_pos = 0.5 * cddpulse(cdd_order - 1, q);

    if( cdd_order % 2 == 0)
    {

        if( k <= npulse /  2 )
        {
            res = lower_order_pos;
        }
        else
        {
            res = 0.5 + lower_order_pos;
        }
    }
    else
    {
        if( k <= (npulse - 1) /2 )
        {
            res = lower_order_pos;
        }
        else if ( k == (npulse + 1) / 2 )
        {
            res = 0.5;
        }
        else
        {
            res = 0.5 + lower_order_pos;
        }
    }
    return res;
}
